#!/usr/bin/python

from Bio.Emboss.Applications import NeedleCommandline
from Bio.Emboss.Applications import WaterCommandline
from Bio import SeqIO
from Bio import AlignIO
import re
import os
import numpy
from pylab import *


class compare:
	
	def __init__(self,fasta):
		
		# Set Cutoff
		self.cutoff = 10
		self.fastas = SeqIO.parse(fasta,'fasta')
		self.water = WaterCommandline(gapopen=100,gapextend=8,outfile="stdout")
		self.slider()
			
	def slider(self):
		for fasta in self.fastas:
			self.pairs = []
			self.scores = []
			self.build_pairs(fasta)
			self.ssearch()
			self.graph()
		os.system("open slide.png")
		return
	
	def build_pairs(self,fasta):
		end = len(fasta.seq)
		for i in range(end):
			pos = i+1
			subject = fasta.seq[0:end-pos]
			target = fasta.seq[pos:end]
			if len(subject) < self.cutoff:
				continue
			self.pairs.append((subject,target))
			
		return
	
	def ssearch(self):
		for pair in self.pairs:
			self.water.asequence="asis:"+pair[0]
			self.water.bsequence="asis:"+pair[1]
			res= self.water()[0]
			score = float(re.search("Score:\s+(\d+\.?\d+?)",res).groups()[0])
			self.scores.append(score/len(pair[0]))
	
	def graph(self):
		aa = len(self.scores)
		plot ( arange(1,len(self.scores)+1),self.scores,'-',label='L')
		xlabel('Query Position of '+str(aa)+' aa')
		ylabel('Lambda Score')
		legend('L')
		title('Position vs Lambda score | Internal Repeats')
		savefig("slide.png",dpi=(1024/8))
		
		#close()